<?php

class persediaancontroller extends CI_Controller
{
	
	function __construct(){
		parent::__construct();
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->model('persediaan_model');
		$this->load->model('return_pembeliaan_model');
		$this->load->model('returpembelian_model');
		$this->load->model('transaksibankpembelian_model');
		$this->load->model('pembelian_model');
		$this->load->model('delaypembelian_model');
	}
	
	function index()
	{
		$data = array(
			'data_array' => $this->persediaan_model->getPersediaanAll(),
			'page_title' => 'Purchasing > Persediaan Barang',
			'name' => $this->session->userdata('fullname'),
			'message' => ''	
		);
		$content = array('content' => 'purchasing/persediaan/inputpersediaan');
		$this->template->load('templates/default',$content,$data);
	}
	
	function tambah()
	{	
		$data = array(
			'page_title' => 'Purchasing > Persediaan Barang',
			'name' => $this->session->userdata('fullname'),
			'nofaktur' => $this->persediaan_model->getFakturNo(),
			'nopo' => $this->persediaan_model->getnpo(),
			'message' => ''	
		);
		$content = array('content' => 'purchasing/persediaan/tambahpersediaan');
		$this->template->load('templates/default',$content,$data);
	}
	
	function ambil_data_pesanan_ajax()
	{
		$cek = $this->session->userdata('fullname'); 
		if(!empty($cek))
		{
			
 			$this->cart->destroy();
			$data["kode_pesanan"] = $_GET["kode_pesanan"];
			//$data["stts"] = "Ok";
			$sess_data['kode_pesanan'] = $data["kode_pesanan"];
			$this->session->set_userdata($sess_data);
			
			$cek = $this->persediaan_model->cekData($_GET["kode_pesanan"]); 
			if($cek>0)
			{
				$kode_pesanan = $_GET['kode_pesanan'];
				?> <script> window.location="<?php echo site_url(); ?>/persediaancontroller/"; </script> <?php
			}
			else
			{
			$dt_pelanggan = $this->persediaan_model->manualQuery("select a.KodeSupplier, c.Suppliername,a.Tanggalpo,count(b.KodeDetailBarang) as jum_item,sum(b.Quantity) as jum_barang from order_product a,transaction_order_product b, supplier c
where a.NoPo=b.NoPo and a.KodeSupplier=c.KodeSupplier and a.NoPo='".$this->session->userdata('kode_pesanan')."'");
			foreach($dt_pelanggan->result() as $dp)
			{
				$bc['tgl_po'] = $dp->Tanggalpo;
				$bc['jum_item'] =  $dp->jum_item;
				$bc['jum_barang'] = $dp->jum_barang;
				$bc['supplierkode'] = $dp->KodeSupplier;
				$bc['suppliername'] = $dp->Suppliername;
			}
			
			$bc['dt_order_detail'] = $this->persediaan_model->manualQuery("select a.KodeDetailBarang, b.Productname, a.Quantity,a.HargaBarang from transaction_order_product a left 
			join detail_product b on a.KodeDetailBarang=b.KodeDetailBarang where a.NoPo='".$this->session->userdata('kode_pesanan')."'");
			$in_cart = array();
			foreach($bc['dt_order_detail']->result() as $dpd)
			{
				$in_cart[] = array(
				'id'      => $dpd->KodeDetailBarang,
				'qty'     => $dpd->Quantity,
				'price'   => $dpd->HargaBarang,
				'name'    => $dpd->Productname,
            	'options' => array('QtyTerkirim' => $dpd->Quantity, 'QtyReturn' => $dpd->Quantity, 'QtyDelay' => $dpd->Quantity));
			}
			$this->cart->insert($in_cart);
			?>
			<script>
			function hitBayar(){
				var total = parseInt(document.frm.total.value);
				var bayar = parseInt(document.frm.bayar.value);
				var sisa = bayar-total;
				if(bayar<total)
				{
					document.frm.kembalian.value=0;
					document.frm.hutang.value=Math.abs(sisa)+<?php echo $bc['hutang']; ?>;
				}
				else
				{
					document.frm.kembalian.value=sisa;
					document.frm.hutang.value=<?php echo $bc['hutang']; ?>;
				}
				if(document.frm.bayar_hutang.checked==true)
				{
					bayarHutang();
				}
				document.frm.btnsimpan.disabled=false;
			}
			function bayarHutang(){
				var total = parseInt(document.frm.total.value);
				var bayar = parseInt(document.frm.bayar.value);
				var sisa = bayar-total;
				if(document.frm.bayar_hutang.checked==true)
				{
					if(bayar<total)
					{
						document.frm.kembalian.value=0;
						document.frm.hutang.value=Math.abs(sisa)+<?php echo $bc['hutang']; ?>;
					}
					else
					{
						var hit_hutang = sisa-<?php echo $bc['hutang']; ?>;
						var hit_hutang_tampil = Math.abs(sisa-<?php echo $bc['hutang']; ?>);
						if(<?php echo $bc['hutang']; ?>>sisa)
						{
							document.frm.hutang.value=Math.abs(sisa-<?php echo $bc['hutang']; ?>);
							document.frm.kembalian.value=0;
						}
						else
						{
							document.frm.hutang.value=0;
							document.frm.kembalian.value=hit_hutang;
						}
					}
				}
				else
				{
					if(bayar>total)
					{
						document.frm.hutang.value=<?php echo $bc['hutang']; ?>;
						document.frm.kembalian.value=sisa;
					}
					else
					{
						var hit_hutang = sisa-<?php echo $bc['hutang']; ?>;
						var hit_hutang_tampil = Math.abs(sisa-<?php echo $bc['hutang']; ?>);
						if(<?php echo $bc['hutang']; ?>>sisa)
						{
							document.frm.hutang.value=Math.abs(sisa-<?php echo $bc['hutang']; ?>);
							document.frm.kembalian.value=0;
						}
						else
						{
							document.frm.hutang.value=0;
							document.frm.kembalian.value=hit_hutang_tampil;
						}
					}
				}
			}
			

function hitungUlang(){
	var input_tipe = document.getElementsByTagName("textarea");
	var select_tipe = document.getElementsByTagName("select");
	var arr_harga = new Array();
	var arr_jum = new Array();
	for(var j = 0; j<input_tipe.length; j++)
	{
		if (input_tipe[j].name=="harga[]"){
			arr_harga[j] = input_tipe[j].value;
		}
	}
	for(var i = 0; i<select_tipe.length; i++)
	{
		if (select_tipe[i].name=="qty_dikirim[]"){
			arr_jum[i] = select_tipe[i].value;
		}
	}
	var sum = 0;
	var jum_total =0;
	for(var k=0; k< arr_harga.length; k++) {
		sum = arr_harga[k]*arr_jum[k+1];
		jum_total +=arr_harga[k]*arr_jum[k+1];
		document.getElementById('subtotal'+k).innerHTML = addCommas(sum);
		document.getElementById('total').innerHTML = addCommas(jum_total);
		document.frm.total.value = jum_total;
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
			</script>
			<table width="90%" cellpadding="3" cellspacing="0">
			<tr>
			  <td width="110"><strong>Tanggal PO</strong></td><td width="20" align="center"><strong>:</strong></td><td width="325">
				<input type="text" value="<?php echo $bc['tgl_po']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" /><input type="hidden" value="<?php echo $bc['tgl_po']; ?>" name="tanggal_po" />
				<td width="110"><strong>Banyak Item/Barang</strong></td><td width="21" align="center"><strong>:</strong></td><td width="288">
				<input type="text" value="<?php echo $bc['jum_item']; ?>" class="input-read-only" readonly="true" 
				 style="width:130px;" name="jum_item" />
				 <input type="text" value="<?php echo $bc['jum_barang']; ?>" class="input-read-only" readonly="true" 
				 style="width:130px;" name="qty_barang_terjual" /></td></tr>
				<tr><td width="110"><strong>Kode Supplier</strong></td><td width="20" align="center"><strong>:</strong></td><td><input type="text" value="<?php echo $bc['supplierkode']; ?>" class="input-read-only" readonly=
				"true" style="width:280px;" name="kode_supplier" /></td>
				<td width="110"><strong>Nama Supplier</strong></td><td align="center"><strong>:</strong></td><td>
				<input type="text" value="<?php echo $bc['suppliername']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" name="nama_supplier" /></td></tr>
                 <tr>
                 <td width="110"><strong>Keterangan</strong></td><td width="20" align="center"><strong>:</strong></td><td><input type="text" value="" style="width:280px;" name="keterangan" /></td>
                 </tr>
				<!--<tr><td width="110">Alamat Pelanggan</td><td>:</td><td>
				<input type="text" value="<?php //echo $bc['alamat']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" name="alamat" />
				<td width="110">No. Telepon</td><td>:</td><td>
				<input type="text" value="<?php //echo $bc['no_telp']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" name="no_telp" /></td></tr>
				<tr><td width="110">Tanggal Pesanan</td><td>:</td><td>
				<input type="text" value="<?php //echo $bc['tgl_pesanan']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" name="tanggal_pesanan" />
				<td width="110">Kota - Provinsi</td><td>:</td><td>
				<input type="text" value="<?php //echo $bc['kota_provinsi']; ?>" class="input-read-only" readonly="true" 
				 style="width:280px;" name="kota_provinsi" /></td></tr>-->
			</table>
		<h3>Data Persediaan Barang</h3>
			<table border="1" cellpadding="3" cellspacing="0" width="90%" style=" border-collapse: collapse;" class="record">
			<tr style="background-color:#333; color:#FFFFFF;" align="center">
				<td width="20">No.</td>
				<td width="30">Kode Barang</td>
				<td width="60">Nama Barang</td>
				<td width="30" align="center">Jumlah Pesanan</td>
				<td width="30"><table width="70%"><tr><td width="40">Dikirim</td></tr></table></td>
				<td width="30"><table width="70%"><tr><td width="40">Delay</td></tr></table></td>
                <td width="30"><table width="70%"><tr><td width="40">Return</td></tr></table></td>
				<!--<td>Harga</td>
				<td width="150">Sub Total</td>-->
			</tr>
			<?php $i = 1; $no=1; $js=0; ?>
			<?php foreach($this->cart->contents() as $items):?>
			
			<?php echo form_hidden('rowid[]', $items['rowid']); ?>
			<tr class="content">
				
				<td class="td-keranjang"><?php echo $no; ?></td>
				<td class="td-keranjang"><?php echo $items['id']; ?></td>
				<td class="td-keranjang"><?php echo $items['name']; ?></td>
				<td class="td-keranjang" align="center"><?php echo $items['qty']; ?></td>
				<td class="td-keranjang">
				<table width="100%"><tr>
				<?php 
				$terkirim = 0;
				foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value)
				{
					switch ($option_name) {
						case "QtyTerkirim":
							echo '<td width="50">';
							$terkirim = $option_value;
							?>
							<select name="qty_dikirim[]" class="input-read-only" style="width:55px;" onchange="hitungUlang();">
								<?php
								//for($j=0;$j<=$items['qty']-$terkirim;$j++)
								for($j=0;$j<=$terkirim;$j++)
								{
									echo "<option value='".$j."'>".$j."</option>";
								}	
								?>
							</select>
							<input type="hidden" name="qty_terkirim[]" value="<?php echo $option_value; ?>" />
							<?php
							echo '</td>';
							break;
					}
				} 
				?>
				</tr></table>
				</td>
				<td class="td-keranjang">
				<table width="100%"><tr>
				<?php 
				$terkirim = 0;
				foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value)
				{
					switch ($option_name) {
						case "QtyDelay":
							echo '<td width="50">';
							$terkirim = $option_value;
							?>
							<select name="qty_delay[]" class="input-read-only" style="width:55px;" onchange="hitungUlang();">
								<?php
								//for($j=0;$j<=$items['qty']-$terkirim;$j++)
								for($j=0;$j<=$terkirim;$j++)
								{
									echo "<option value='".$j."'>".$j."</option>";
								}	
								?>
							</select>
							<?php
							echo '</td>';
							break;
					}
				} 
				?>
				</tr></table>
				</td>
                <td class="td-keranjang">
				<table width="100%"><tr>
				<?php 
				$terkirim = 0;
				foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value)
				{
					switch ($option_name) {
						case "QtyReturn":
							echo '<td width="50">';
							$terkirim = $option_value;
							?>
							<select name="qty_return[]" class="input-read-only" style="width:55px;" onchange="hitungUlang();">
								<?php
								//for($j=0;$j<=$items['qty']-$terkirim;$j++)
								for($j=0;$j<=$terkirim;$j++)
								{
									echo "<option value='".$j."'>".$j."</option>";
								}	
								?>
							</select>
							<?php
							echo '</td>';
							break;
					}
				} 
				?>
				</tr></table>
				</td>
				<!--<td class="td-keranjang">Rp. <textarea class="input-read-only" style="resize:none; width:80px; height:18px; font-family:Arial;" readonly="readonly" name="harga[]"><?php //echo $items['price']; ?></textarea></td>
				<td class="td-keranjang" id="subtotal<?php //echo $js; ?>"></td>-->
			</tr>
	  	
	  	<?php $i++; $no++; $js++; ?>
		<?php endforeach; ?>
			<!--<tr height="40">
				<td colspan="7">Total Bayar <input type="hidden" value="" name="total" /></td>
				<td id="total">Rp. </td>
			</tr>
			<tr>
				<td colspan="7">Jumlah Yang Dibayar</td>
				<td>Rp. <input type="text" class="input-read-only" style="width:110px;" name="bayar" onchange="hitBayar();" /></td>
			</tr>
			<tr>
				<td colspan="7">Kembalian | <input type="checkbox" name="bayar_hutang" id="bayar_hutang" onclick="bayarHutang();" /><label for="bayar_hutang">Bayar hutang...???</label></td>
				<td>Rp. <input type="text" class="input-read-only" readonly="true" style="width:110px;" name="kembalian" /></td>
			</tr>
			<tr>
				<td colspan="7">Hutang</td>
				<td>Rp. <input type="text" class="input-read-only" readonly="true" style="width:110px;" name="hutang" value="<?php //echo $bc['hutang']; ?>" /></td>
			</tr>-->
			</table>
			<div class="cleaner_h10"></div>
			<!--<input type="submit" class="btn-kirim-login" value="Simpan Dan Cetak Faktur" disabled="disabled" name="btnsimpan">-->
            <input type="submit" class="btn-kirim-login" value="Simpan Dan Cetak Faktur" name="btnsimpan">
			<?php
			}
		}
	}
	
	function tambah_faktur()
	{
		$cek = $this->session->userdata('fullname');
		if(!empty($cek))
		{
			$total = $this->cart->total_items();
			$qty_terkirim = $this->input->post('qty_terkirim'); 
			$qty_dikirim = $this->input->post('qty_dikirim'); 
			$qty_delay = $this->input->post('qty_delay'); 
			$qty_return = $this->input->post('qty_return'); 
			$id_detail['kode_pesanan'] = $this->input->post('kode_pesanan');  
			
			$i = 0;
			$jum_terkirim = 0;
			$jum_amountkirim = 0;
			$jum_delay = 0;
			$jum_amountdelay = 0;
			$ttlqty = 0;
			$ttlamount = 0;
			$discount = 0;
			$ppn = 0;
			$kdnoreturok 	= $this->returpembelian_model->getReturnNoCode();
			
			foreach($this->cart->contents() as $items)
			{
				$totAll = $qty_dikirim[$i] + $qty_delay[$i] + $qty_return[$i]; 
				if ($totAll == $items['qty'])
				{
					//insert into faktur detail
					if ($qty_dikirim[$i] > 0)
					{
						$kodedetailid = $this->persediaan_model->getdetailid();
						//echo 'krm'.$qty_dikirim[$i]; echo '<br>';
						//print_r($kodedetailid);exit;
						$amountTerkirim = $qty_dikirim[$i] * $items['price']; 
						$this->persediaan_model->setNoFaktur($_POST['kode_faktur']);
						$this->persediaan_model->setIDdetail($kodedetailid);
						$this->persediaan_model->setNoPo($id_detail['kode_pesanan']);
						$this->persediaan_model->setKodeDetailBarang($items['id']);
						$this->persediaan_model->setQuantity($qty_dikirim[$i]);
						$this->persediaan_model->setDiscount($discount);
						$this->persediaan_model->setPpn($ppn);
						$this->persediaan_model->setAmount($amountTerkirim); 
						$this->persediaan_model->insertFakturDetail(); 
					}
					
					//insert into return pembeliaan
					if ($qty_return[$i] > 0)
					{						
						$kdidok		= $this->returpembelian_model->getdetailid();
						 
						$kodeBrg	= $items['id'];
						$hrgBrg		= $items['price'];
						$qtydet 	= $qty_return[$i];
						$disc 		= 0;
						$amountReturn = $qty_return[$i] * $items['price'];
						$ttlqty 	= $ttlqty + $qtydet;
						$ttlamount 	= $ttlamount + $amountReturn;
					
						
						$this->returpembelian_model->setReturnNo($kdnoreturok);
						$this->returpembelian_model->setIDdetail($kdidok);
						$this->returpembelian_model->setKodeDetailBarang($kodeBrg);
						$this->returpembelian_model->setHargaBarang(intval($hrgBrg));
						$this->returpembelian_model->setQTY(intval($qtydet));
						$this->returpembelian_model->setDiscount($disc);
						$this->returpembelian_model->setAmount($amountReturn);			
						$this->returpembelian_model->insertdetail();
					
						/*$noreturn = $this->return_pembeliaan_model->generateReturnNo(); 
						$amountReturn = $qty_return[$i] * $items['price']; 
						$this->return_pembeliaan_model->setReturnNo($noreturn);
						$this->return_pembeliaan_model->setKodeSupplier($_POST['kode_supplier']);
						$this->return_pembeliaan_model->setKodeBarang($items['id']);
						$this->return_pembeliaan_model->setNoPo($id_detail['kode_pesanan']);
						$datereturn = date('Y-m-d');
						$this->return_pembeliaan_model->setDateReturn($datereturn);
						$this->return_pembeliaan_model->setQuantity($qty_return[$i]);
						$this->return_pembeliaan_model->setPrice($amountReturn);
						$this->return_pembeliaan_model->setKeterangan($_POST['keterangan']);
						$this->return_pembeliaan_model->setCreatedBy($this->session->userdata('userid'));
						$tanggal=date('Y-m-d H:i:s', strtotime('now'));
						$this->return_pembeliaan_model->setCreatedOn($tanggal);
						$this->return_pembeliaan_model->setLastupdateby($this->session->userdata('userid'));
						$this->return_pembeliaan_model->setLastupdateon($tanggal);
						$this->return_pembeliaan_model->insertReturnBeli();*/ 
					}
					
					//insert transaction delay pembeliaan
					if ($qty_delay[$i] > 0)
					{
						$kdiddetailok	= $this->delaypembelian_model->getdetailid();
						
						$amountDelay = $qty_delay[$i] * $items['price'];
						$this->delaypembelian_model->setNodelay($this->delaypembelian_model->getNodelayCode());
						$this->delaypembelian_model->setIDdetail($kdiddetailok);
						$this->delaypembelian_model->setKodeDetailBarang($items['id']);
						$this->delaypembelian_model->setQuantity($qty_delay[$i]);
						$this->delaypembelian_model->setDiscount($discount);
						$this->delaypembelian_model->setAmount($amountDelay);
						$this->delaypembelian_model->insertdetail(); 
					}
				}
				
				$jum_terkirim = $jum_terkirim + $qty_dikirim[$i]; 
				$jum_amountkirim = $jum_amountkirim+$amountTerkirim ; 
				$jum_delay = $jum_delay + $qty_delay[$i]; 
				$jum_amountdelay = $jum_amountdelay + $amountDelay; 
				
				$i++;
			}

			//insert header faktur
			$datefaktur = date('Y-m-d');
			$this->persediaan_model->setDateFaktur($datefaktur);
			$this->persediaan_model->setTotalQuantity($jum_terkirim);
			$this->persediaan_model->setTotalAmount($jum_amountkirim);
			$this->persediaan_model->setKeterangan($_POST['keterangan']);
			$this->persediaan_model->setCreatedBy($this->session->userdata('userid'));
			$tanggal=date('Y-m-d H:i:s', strtotime('now'));
			$this->persediaan_model->setCreatedOn($tanggal);
			$this->persediaan_model->setLastupdateby($this->session->userdata('userid'));
			$this->persediaan_model->setLastupdateon($tanggal);
			$this->persediaan_model->insertFakturHeader(); 
			
			//insert header RETURN
			$this->returpembelian_model->setReturnNo($kdnoreturok);
			$this->returpembelian_model->setKodeSupplier($_POST['kode_supplier']);
			$this->returpembelian_model->setNoPo($id_detail['kode_pesanan']);
			$this->returpembelian_model->setDateReturn($datefaktur);
			$this->returpembelian_model->setQuantity($ttlqty);
			$this->returpembelian_model->setPrice($ttlamount);
			$this->returpembelian_model->setKeterangan($_POST['keterangan']);
			$this->returpembelian_model->setCreatedBy($this->session->userdata('userid'));		
			$this->returpembelian_model->setCreatedOn($tanggal);
					
			$this->returpembelian_model->insert();
						
			//update PO status
			
			$this->pembelian_model->setNoPo($id_detail['kode_pesanan']);
			$this->pembelian_model->deletepembelian();		
			
			//insert delay header
			if ($jum_delay > 0)
			{ 
				$this->delaypembelian_model->setNodelay($this->delaypembelian_model->getNodelayCode());
				$this->delaypembelian_model->setDatedelay($tanggal);
				$this->delaypembelian_model->setNoPo($id_detail['kode_pesanan']);
				$this->delaypembelian_model->setTotalQuantity($jum_delay);
				$this->delaypembelian_model->setTotalAmount($jum_amountdelay);
				$this->delaypembelian_model->setDiscount($discount);
				$this->delaypembelian_model->setKeterangan($_POST['keterangan']);
				$status = "D";
				$this->delaypembelian_model->setStatus($status);
				$this->delaypembelian_model->setCreatedBy($this->session->userdata('userid'));
				$tanggal=date('Y-m-d H:i:s', strtotime('now'));
				$this->delaypembelian_model->setCreatedOn($tanggal);
				$this->delaypembelian_model->insert(); 		
			}
			
			$this->cart->destroy();
			redirect('persediaancontroller');
			//header('location:'.base_url().'persediaancontroller');


		}
	}
	
	function cetak_faktur()
	{
		$idkdNofaktur 	= $this->uri->segment(3);
		
		$this->transaksibankpembelian_model->setNoFaktur($idkdNofaktur);
		$ambilnopook	= $this->transaksibankpembelian_model->ambilnopoaja();
		$this->transaksibankpembelian_model->setNoPo($ambilnopook[0]->NoPo);
		
		$dataprofile = array(
			'page_title' => 'Purchasing > Penerimaan Barang',
			'name' => $this->session->userdata('fullname'),
			'kodefktrno'=> $this->transaksibankpembelian_model->ambilnofaktur(),
			'kodesuppfktr'=> $this->transaksibankpembelian_model->ambilsupplier(),
			'transfktr' => $this->transaksibankpembelian_model->getListfakturdelay()	
		);		
		$content = array(
			'content' => 'purchasing/persediaan/formfakturpembelian'
		);
		$this->template->load('templates/default',$content,$dataprofile);
		
	}
}
?>